package com.cryptooj.project.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.cryptooj.project.common.ErrorCode;
import com.cryptooj.project.exception.BusinessException;
import com.cryptooj.project.judge.codesandbox.CodeSandbox;
import com.cryptooj.project.judge.codesandbox.model.ExecuteCodeRequest;
import com.cryptooj.project.judge.codesandbox.model.ExecuteCodeResponse;

/**
 *  远程代码沙箱
 *  （实际业务调用的代码沙箱，用linux中的docker实现）
 * */
public class RemoteCodeSandbox implements CodeSandbox {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("调用远程代码沙箱--");
        try{
            String ping = "http://192.168.47.129:8090/health";
            String pong = HttpUtil.createGet(ping)
                    .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                    .execute() // 这里执行
                    .body();
            System.out.println(pong);
        }catch (Exception e){
            e.printStackTrace();
        }
        String url = "http://192.168.47.129:8090/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(json)
                .execute() // 这里执行
                .body();
        if(StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"调用远程代码沙箱失败");
        }
        return JSONUtil.toBean(responseStr,ExecuteCodeResponse.class);
    }
}
